package com.idlecode.panel.tool;

import cn.hutool.core.util.StrUtil;
import com.idlecode.service.RemoveBomService;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.TextComponentAccessor;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;

import javax.swing.*;
import java.awt.*;
import java.io.File;

/**
 * @program: IdleCode
 * @description
 * @author: rongjuwei
 * @create: 2024-11-07 08:47
 **/
public class RemoveBomPanel extends JPanel {

    public RemoveBomPanel(Project project) {
        // 垂直排列
        setLayout(new BorderLayout());

        JTextArea textArea = createTextArea();
        add(textArea, BorderLayout.CENTER);

        JPanel filePanel = createFilePanel(textArea);
        add(filePanel, BorderLayout.NORTH);
    }

    private JTextArea createTextArea() {
        JTextArea textArea = new JTextArea(10, 30);
        textArea.setText(null);
        textArea.setLineWrap(true);  // 启用自动换行
        textArea.setWrapStyleWord(true);  // 单词为单位换行
        textArea.setEditable(false);  // 不可编辑
        Font defaultFont = UIManager.getFont("Label.font");
        Font font = defaultFont.deriveFont(14f); // 设置字体大小
        textArea.setFont(font);
        return textArea;
    }

    private JPanel createFilePanel(JTextArea textArea) {
        JPanel filePanel = new JPanel();
        filePanel.setLayout(new BoxLayout(filePanel, BoxLayout.X_AXIS));
        filePanel.add(Box.createRigidArea(new Dimension(20, 0)));
        filePanel.add(new JLabel("文件路径"));

        TextFieldWithBrowseButton fileChooser = createFileChooser(textArea);
        filePanel.add(fileChooser);

        JButton operationButton = new JButton("清除BOM");
        operationButton.addActionListener(e -> handleRemoveBOM(fileChooser, textArea));
        filePanel.add(operationButton);
        filePanel.add(Box.createHorizontalGlue());

        return filePanel;
    }

    private TextFieldWithBrowseButton createFileChooser(JTextArea textArea) {
        String removeBomPath = RemoveBomService.getInstance().getRemoveBomPath();
        File defaultPath = getDefaultPath(removeBomPath);
        // 将默认路径转换为 VirtualFile
        VirtualFile defaultVirtualFile = defaultPath != null ? VfsUtil.findFileByIoFile(defaultPath, true) : null;
        // 创建文件选择描述符
        FileChooserDescriptor fileChooserDescriptor = new FileChooserDescriptor(true, true, false, false, false, false);
        // 创建 TextFieldWithBrowseButton
        TextFieldWithBrowseButton fileChooser = new TextFieldWithBrowseButton();
        // 添加文件选择器监听器，并设置默认路径
        fileChooser.addBrowseFolderListener(
                "请选择文件或文件夹",
                "提示：只会清除.java格式文件的BOM",
                null,
                fileChooserDescriptor,
                TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT,
                false
        );
        // 在文本框中设置初始值
        if (defaultPath != null && defaultPath.exists()) {
            fileChooser.setText(defaultPath.getAbsolutePath());
        }
        return fileChooser;
    }

    private File getDefaultPath(String removeBomPath) {
        if (StrUtil.isBlank(removeBomPath)) {
            return new File(System.getProperty("user.home"), "Desktop");
        }
        File removeBomFilePath = new File(removeBomPath);
        if (!removeBomFilePath.exists()) {
            return new File(System.getProperty("user.home"), "Desktop");
        }
        return removeBomFilePath;
    }

    private void handleRemoveBOM(TextFieldWithBrowseButton fileChooser, JTextArea textArea) {
        String filePath = fileChooser.getText();
        if (filePath == null || filePath.isEmpty()) {
            Messages.showMessageDialog("请先选择文件或文件夹！", "错误", Messages.getErrorIcon());
            return;
        }
        RemoveBomService.count = 0;
        File file = new File(filePath);
        try {
            if (file.isFile()) {
                RemoveBomService.getInstance().removeBOMFromFile(file, textArea);
            } else if (file.isDirectory()) {
                RemoveBomService.getInstance().processDirectory(file, textArea);
            }
            Messages.showMessageDialog(StrUtil.format("BOM清除成功！\n共修改{}个文件", RemoveBomService.count),
                    "提示",
                    Messages.getInformationIcon());
        } catch (Exception ex) {
            Messages.showMessageDialog(ex.getMessage(), "错误", Messages.getErrorIcon());
        }
    }
}
